package cn.gov.pbc.gd.credit.center.service.util;

import java.util.Map;

import org.jsoup.Connection;
import org.jsoup.Connection.Method;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.liu.tools.HttpUtil;
import com.liu.tools.StrUtil;

public class JsoupUtil {
	
	/**
	 * @author liuxingmi
	 * @datetime 2017年6月6日 下午3:10:05
	 * @desc jsoup Post请求
	 * @param addr
	 * @param reqMethod
	 * @param data
	 * @param encode
	 * @param cookies
	 * @throws Exception void
	 */
	public static Document post(String addr, String data, String encode, Map<String, String> cookies) throws Exception{
		
		Connection conn = Jsoup.connect(addr);     
		conn.timeout(60000);
		conn.method(Method.POST);
		conn.requestBody(data);
		//conn.data(arg0)
		conn.followRedirects(false); 
		conn.postDataCharset(encode);
		conn.cookies(cookies);
		Response response = conn.execute();     
		String html = response.body();
		Document document = Jsoup.parse(html);
	    return document;
		
	}
	
	
	/**
	 * @author liuxingmi
	 * @datetime 2017年6月6日 下午3:10:05
	 * @desc jsoup Post请求
	 * @param addr
	 * @param reqMethod
	 * @param data
	 * @param encode
	 * @param cookies
	 * @throws Exception void
	 */
	public static String postBody(String addr, String data, String encode, Map<String, String> cookies) throws Exception{
		
		String cookieStr = getCookieStr(cookies);

		String html = HttpUtil.httpPostDataByCookies(addr, data, HttpUtil.CT_TYPE_APPLICATION, encode, cookieStr, 60000);
		
	    return html;
		
	}
	
	/**
	 * @author liuxingmi
	 * @datetime 2017年6月6日 下午5:54:10
	 * @desc 
	 * @param addr
	 * @param encode
	 * @param cookies
	 * @return Document
	 * @throws Exception 
	 */
	public static Document get(String addr, String encode, Map<String, String> cookies) throws Exception{
		
		Connection conn = Jsoup.connect(addr); 
		conn.timeout(60000);
		conn.method(Method.GET);
		conn.followRedirects(false); 
		conn.postDataCharset(encode);
		conn.cookies(cookies);
		Response response = conn.execute();     
		String html = response.body();
		Document document = Jsoup.parse(html);
	    return document;
		
	}
	
	
	public static String getCookieStr(Map<String, String> cookies) {
		
		String cookieStr = "";
		for (Map.Entry<String, String> entry : cookies.entrySet()) {
			cookieStr += entry.getKey() + "=" + entry.getValue() + ";";
		}
		if(StrUtil.isNotNull(cookieStr)){
			cookieStr = cookieStr.substring(0, cookieStr.length() - 1);
		}
		return cookieStr;
	}

}
